package com.jiepos.mpos.pay;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.RspCodeConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppCustomBankcardDao;
import com.jiepos.mpos.common.dao.AppCustomerInfoDao;
import com.jiepos.mpos.common.dao.AppPayDao;
import com.jiepos.mpos.common.dao.InsServiceParamDao;
import com.jiepos.mpos.common.dao.LogAbstractDao;
import com.jiepos.mpos.common.service.AbrBaseHttpService;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.MathUtils;
import com.jiepos.mpos.core.util.StringUtils;


/**
 * 
 * 
 * <p>标题: —— 提现申请表服务类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos] 
 * @Package com.jiepos.mpos.biz.channel.service 
 * @author 张学涛
 * @version 1.0
 * @since 2017年10月16日上午11:43:05
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class LogAbstractService extends AbrBaseHttpService {
	
	private static final Logger _log = LoggerFactory.getLogger(LogAbstractService.class);
	
	@Autowired
	private LogAbstractDao logAbstractDao;
	@Autowired
	private AppCustomerInfoDao appCustomerInfoDao;	
	@Autowired
    private InsServiceParamDao insServiceParamDao;
	@Autowired
	private AppCustomBankcardDao appCustomBankcardDao;
	
	@Autowired
	private AppPayDao appPayDao;
	
	/**
	 * 保存提现流水
	 * @param payResMap
	 */
	public Map<String,String> saveLogAbstract(Map<String,String> payResMap){
		_log.info("初始化提现流水请求的map=[{}]", payResMap);
		try {
			String uuid = IDFactoryUtil.getUUID();
			Map<String,Object> paramInfoMap = appPayDao.getCustomInsInfo(uuid,String.valueOf(payResMap.get("custom_no")),String.valueOf(payResMap.get("service_uuid")),String.valueOf(payResMap.get("service_param_uuid")),String.valueOf(payResMap.get("custom_level")));
			if(paramInfoMap==null||paramInfoMap.isEmpty()||!"1".equals(paramInfoMap.get("result"))){
				return getRspMap(RspCodeConstant.RSPCODE_300005, null, null);
			}
			Map<String,Object> cardInfoMap = appPayDao.getCustomInfo(String.valueOf(payResMap.get("custom_no")));
			if(cardInfoMap==null||cardInfoMap.isEmpty()){
				return getRspMap(RspCodeConstant.RSPCODE_300020, null, null);
			}
			//App_Custom_InfEntity custom_Info = appCustomerInfoDao.findByParam("custom_no", payResMap.get("custom_no"));
			Map<String, Object> bankCardInfo = appPayDao.getCustomBankCardInfo(String.valueOf(cardInfoMap.get("custom_uuid")));
			if(bankCardInfo==null||bankCardInfo.isEmpty()){
				return getRspMap(RspCodeConstant.RSPCODE_300027, null, null);
			}
			StringBuffer sb=new StringBuffer();
			sb.append("INSERT INTO ");
			sb.append(Table.T_APP_LOG_ABSTRACT);
			sb.append(" (abstract_uuid,ins_uuid,apply_no,custom_uuid,custom_bankcard_uuid,apply_dt,apply_ts,account_type,service_uuid,");
			sb.append("service_param_uuid,apply_amt,audit_stlflag,rsp_code,rsp_msg,");
			sb.append("rec_st,rec_crt_ts,rec_upd_ts,rec_upd_usr_id,last_oper_in)");
			sb.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
			
			String applyNo=IDFactoryUtil.getId();			
			List paramList = new ArrayList();
			paramList.add(uuid);
			paramList.add(String.valueOf(paramInfoMap.get("service_ins_uuid")));
			paramList.add(applyNo);
			paramList.add(cardInfoMap.get("custom_uuid"));
			paramList.add(StringUtils.objToString(bankCardInfo.get("bankcard_uuid")));
			paramList.add(DateUtil.getCurrDateStr());
			paramList.add(DateUtil.getCurrTimeStr());
			paramList.add(payResMap.get("acc_type"));
			paramList.add(payResMap.get("service_uuid"));
			paramList.add(payResMap.get("service_param_uuid"));
			paramList.add(MathUtils.div(Double.parseDouble(String.valueOf(payResMap.get("trans_at"))), Double.parseDouble("100"), 2));
			//paramList.add(MathUtils.div(new Double(payResMap.get("withdraw_fee")), new Double(100), 2));			
			paramList.add(SystemConstant.AUDIT_STL_0);			
			paramList.add(SystemConstant.WITHDRAW_CODE_XX);
			paramList.add(String.valueOf(getCashRspCodeListMap().get(SystemConstant.WITHDRAW_CODE_XX)));
			paramList.add(SystemConstant.NORMAL_STATUS);
			paramList.add(new Timestamp(System.currentTimeMillis()));
			paramList.add(new Timestamp(System.currentTimeMillis()));
			paramList.add(payResMap.get("login_id"));
			paramList.add(SystemConstant.OPER_ADD);
			logAbstractDao.update(sb.toString(), paramList);
			
			payResMap.put("apply_no", applyNo);
			payResMap.put("ins_st", String.valueOf(paramInfoMap.get("service_ins_st")));
			return new HashMap();
		} catch (Exception e) {
			_log.error("初始化提现流水发生异常", e);
			return getRspMap(RspCodeConstant.RSPCODE_300016, null, null);
		}
	}
	
	/**
	 * 获取提现申请单号
	 * @return
	 */
	public String getApplyNo(){
		String applyNo = null;
		String dateStr = DateUtil.getCurrDateStr();
		while (true) {
			applyNo = DateUtil.getCurrDateTimeStr() + String.valueOf(IDFactoryUtil.getSixRandom());
			StringBuilder sb = new StringBuilder();
			sb.append("select t1.abstract_uuid,t1.ins_uuid,t1.apply_no,t1.apply_dt from ");		
			sb.append(Table.T_APP_LOG_ABSTRACT);
			sb.append(" t1 where 1=1 ");
			List list = new ArrayList();			
			sb.append( " and t1.apply_no = ? " );
			list.add(applyNo);			
			sb.append( " and t1.apply_dt = ? " );
			list.add(dateStr);					
			List result=logAbstractDao.queryForList(sb.toString(), list);
			if(result.size()==0||result==null){
				break;
			}
		}		
		return applyNo;
	}
	
	/**
	 * 计算手续费
	 * @param payResMap
	 * @return
	 * @throws Exception 
	 */
	public Map<String,String> calculateFee(Map<String,String> payResMap) throws Exception{
		_log.info("初始化提现流水请求的map=[{}]", payResMap);
		Map<String,Object> paramInfoMap = appPayDao.getCustomInsInfo(null,String.valueOf(payResMap.get("custom_no")),String.valueOf(payResMap.get("service_uuid")),String.valueOf(payResMap.get("service_param_uuid")),String.valueOf(payResMap.get("custom_level")));		
		Map<String,Object> cardInfoMap = appPayDao.getCustomInfo(String.valueOf(payResMap.get("custom_no")));
		//App_Custom_InfEntity custom=customerInfoService.getCustomByNo(payResMap.get("custom_no"));
		String custom_level="";
		if(SystemConstant.AUTH_ST_0.equals(String.valueOf(cardInfoMap.get("realname_auth_st")))&&SystemConstant.AUTH_ST_0.equals(String.valueOf(cardInfoMap.get("vip_st")))){
			return getRspMap(RspCodeConstant.RSPCODE_300004, null, null);
		}else if(SystemConstant.AUTH_ST_1.equals(String.valueOf(cardInfoMap.get("vip_st")))){
			custom_level=SystemConstant.CUSTOM_LEVEL_2;
		}else if(SystemConstant.AUTH_ST_1.equals(String.valueOf(cardInfoMap.get("realname_auth_st")))){
			custom_level=SystemConstant.CUSTOM_LEVEL_1;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("select t1.debit_minfee,t1.debit_rate,t1.debit_maxfee from ");
		sb.append(Table.T_APP_INS_SERVICE_PARAM);
		sb.append(" where 1=1 ");
		List list = new ArrayList();			
		sb.append( " and t1.ins_uuid = ? " );
		list.add(String.valueOf(paramInfoMap.get("service_ins_uuid")));			
		sb.append( " and t1.service_uuid = ? " );
		list.add(payResMap.get("service_uuid"));	
		sb.append( " and t1.service_param_uuid = ? " );
		list.add(payResMap.get("service_param_uuid"));
		sb.append( " and t1.custom_level = ? " );
		list.add(custom_level);
		List<Map<String,String>> result=insServiceParamDao.queryForList(sb.toString(), list);
		if(result.size()==0||result==null){
			return getRspMap(RspCodeConstant.RSPCODE_300017, null, null);
		}
		String debit_minfee =String.valueOf(result.get(0).get("debit_minfee"));
		String debit_rate =String.valueOf(result.get(0).get("debit_rate"));
		String debit_maxfee =String.valueOf(result.get(0).get("debit_maxfee"));
		String trans_at=payResMap.get("trans_at");
		Double debit_fee=MathUtils.mul(Double.parseDouble(trans_at),Double.parseDouble(debit_rate));		
		if(debit_fee.compareTo(Double.parseDouble(debit_minfee))<0){
			payResMap.put("withdraw_fee", debit_minfee);
		}else if(debit_fee.compareTo(Double.parseDouble(debit_maxfee))>0){
			payResMap.put("withdraw_fee", debit_maxfee);
		}else{
			payResMap.put("withdraw_fee", debit_fee.toString());
		}
		return null;
	}
	
	/**
	 * 更新流水状态
	 * @param payResMap
	 * @param value
	 */
	public void updateRspCd(Map<String, String> payResMap,String rsp_code,String rsp_msg){
		//_log.info("更新提现流水请求的map=[{}]", payResMap);
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String> values = new HashMap<String, String>();
		String apply_no = String.valueOf(payResMap.get("apply_no"));
		params.put("apply_no", apply_no);		
		values.put("rsp_code", rsp_code);
		if(!StringUtils.isBlank(rsp_msg)){
			values.put("rsp_msg", rsp_msg);
		}
		try {
			update(params, values);
			_log.info("申请单号为[{}]记录更新成功！", apply_no);
		} catch (Exception e) {
			_log.error("申请单号为[{}]记录更新发生异常！",apply_no);
		}
	}
	
	/**
	 * 更新提现流水
	 * @param params
	 * @param values
	 */
	public void update(Map<String, String> params, Map<String, String> values) {

		StringBuffer buffer = new StringBuffer("update T_APP_LOG_ABSTRACT set ");
		for (Map.Entry<String, String> entry : values.entrySet()) {
			if(entry.getValue() != null){
			buffer.append(entry.getKey() + "='" + entry.getValue() + "',");
			}
		}
		buffer.deleteCharAt(buffer.length() - 1);
		buffer.append(" where ");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if(entry.getValue() != null){
			buffer.append(entry.getKey() + "='" + entry.getValue() + "' and ");
			}
		}	
		buffer.append("1=1");
		System.out.println(buffer.toString());
		logAbstractDao.update(buffer.toString());
	}
	
	/**
	 * 查询会员相关信息
	 * @param custom_no
	 * @return
	 */
	public Map<String,String> getWithdrawMap(String custom_no){
		_log.info("查询会员相关信息custom_no="+custom_no);
		if (StringUtils.isBlank(custom_no) || custom_no.equals("undefined")) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("select  t1.certificate_no,t2.super_bank_no,t2.super_bank_nm,t2.settle_bank_no,t2.settle_acct,t2.acct_nm,");
		sb.append("t2.bank_nm,t2.bank_province,t2.bank_locality from ");
		sb.append(Table.T_APP_CUSTOM_INF);
		sb.append(" t1 inner join ");
		sb.append(Table.T_APP_CUSTOM_BANKCARD);
		sb.append(" t2 on t1.custom_uuid=t2.custom_uuid ");
		sb.append(" where t1.rec_st !='0' and t1.custom_no='");
		sb.append(custom_no);
		sb.append("'");
		List<Map<String,String>> result =appCustomerInfoDao.queryForList(sb.toString());
		if(result.size()==0||result==null){
			return null;
		}else{
			return result.get(0);
		}		
	}
	
	/**
	 * 获取结果未知提现记录
	 * @return
	 */
	public List<Map<String, String>> getUnknownWithdraw() {		
		List<Map<String, String>> list = logAbstractDao.getUnknownWithdraw();
		//System.out.println("list:" + list);
		return list;
	}

	/**客户提现申请变更客户余额和增加明细记录*/
	public String updateAbstract(String apply_no){
		_log.info("申请单号为[{}]变更客户余额和增加明细记录！",apply_no);
		try{
			String code= appPayDao.updateAbstract(apply_no);	
			if("1".equals(code)){
				return SystemConstant.RSPCODE_SUCCESS;
			}else{
				return code;
			}
		}catch(Exception e){
			_log.error("变更客户余额和增加明细记录发生异常",e);							
			return SystemConstant.RSPCODE_ERROR;
		}
		
		
	}
	
}
